package com.cloud.message.controller;

import com.cloud.common.bean.PageInfo;
import com.cloud.common.bean.ResultInfo;
import com.cloud.message.constant.ErrorEnum;
import com.cloud.message.dto.ConsumerInsertParamDTO;
import com.cloud.message.dto.ConsumerQueryParamDTO;
import com.cloud.message.entity.Consumer;
import com.cloud.message.service.ConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

/**
 * 消费者接口
 */
@Slf4j
@RestController
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;

    /**
     * 查询消费者
     *
     * @param paramDTO
     * @return ResultInfo
     */
    @PostMapping("/message/consumer/query")
    public ResultInfo<PageInfo<Consumer>> query(@Valid @RequestBody ConsumerQueryParamDTO paramDTO) {
        PageInfo<Consumer> pageInfo = consumerService.getPage(paramDTO);
        return ResultInfo.success().setData(pageInfo);
    }

    /**
     * 添加消费者
     *
     * @param paramDTO
     * @return ResultInfo
     */
    @PostMapping("/message/consumer/insert")
    public ResultInfo<String> insert(@Valid @RequestBody ConsumerInsertParamDTO paramDTO) {
        if (consumerService.exist(paramDTO.getTopic(), paramDTO.getServiceName())) {
            return ErrorEnum.CONSUMER_EXIST.resultInfo();
        }
        Consumer consumer = new Consumer();
        BeanUtils.copyProperties(paramDTO, consumer);
        consumer.setCreateTime(new Date());
        consumerService.save(consumer);
        return ResultInfo.success();
    }

    /**
     * 删除消费者
     *
     * @param id
     * @return ResultInfo
     */
    @PostMapping("/message/consumer/delete")
    public ResultInfo<String> delete(Integer id) {
        consumerService.removeById(id);
        return ResultInfo.success();
    }
}

